import React, {
    Component
} from 'react';
import GridTable from '../../components/display/gridTable';
import ScModal from '../../components/feedback/scModal';
import {
    Button,
    Select,
    Row,
    Col,
    Slider,
    Divider,
    Tooltip,
    AutoComplete
} from 'antd';
import PropsType from 'prop-types';
import {
    fetchMap,
    getStubGroupDetail,
    stubGroupNameTips
} from '../../fetch/fetchApi';
import '../../assets/stylus/com/display/amap.styl';
const Option = Select.Option;
const AMap = window.AMap;

class PsDetail extends Component {
    constructor(props) {
        super(props);
        this.props = props;
        this.state = {
            gridData: null,
            loading: !1,
            loadingmes: '查询',
            dataSource: []
        };
        this.init();
    }

    init() {
        this.tableColumns = [{
            title: '电站名称',
            dataIndex: 'name',
            key: 'name',
            fixed: 'left',
            width: 100,
            className: 'column-nowrap',
            render: (text, record) => (
                <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
        }, {
            title: '直流数',
            dataIndex: 'dcStubCnt',
            key: 'dcStubCnt',
        }, {
            title: '交流数',
            dataIndex: 'acStubCnt',
            key: 'acStubCnt',
        }, {
            title: '计费标准',
            dataIndex: 'totalFeeInfo',
            key: 'totalFeeInfo',
            className: 'column-nowrap',
            render: (text, record) => (
                <Tooltip placement="topLeft" title={text && text.replace(/#/g, '\n')}>
            {text}
          </Tooltip>)
        }, {
            title: '运营类型',
            dataIndex: 'type',
            key: 'type',
        }, {
            title: '电站类型',
            dataIndex: 'stubGroupType',
            key: 'stubGroupType',
            className: 'column-nowrap'
        }, {
            title: '距离',
            dataIndex: 'distanceStr',
            key: 'distanceStr',
        }, {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 100,
            render: (text, record) => (
                <div className="action-wrap">
            <a href="javascript:void(0);" onClick={() => this.showEsDetail(record.key, '电站详情')}>电站详情</a>
            <Divider type="vertical" />
            <a href="javascript:void(0);" onClick={() => this.openTab({
                        'keyId': record.key,
                        'stubGroupId': record.key
                    }, {
                        'key': '010202',
                        titleText: '电桩列表'
                    })}>电桩列表</a>
          </div>
            )
        }];
        this.stubGroupType = {
            '0': '公共',
            '1': '个人',
            '2': '专用开放',
            '3': '专用内部'
        };
        this.opType = {
            '0': '非自营桩群',
            '1': '自营桩群'
        };
        let MapApi = {};
        // 默认10公里
        this.params = {
            gisType: 1,
            distance: 10,
            lowKw: 0,
            highKw: 500
        };
    }

    // 初始化高德地图
    componentDidMount() {
        const map = new AMap.Map('mapContainer', {
            zoom: 12
        });
        this.map = map;
        // 定义默认中心点标识
        this.centerMarker = new AMap.Marker({
            map: map,
            icon: new AMap.Icon({
                size: new AMap.Size(40, 50), //图标大小
                image: "http://webapi.amap.com/theme/v1.3/images/newpc/way_btn2.png",
                imageOffset: new AMap.Pixel(0, -60)
            })
        });
        this.setLocalArea(map);
        map.on('moveend', (ev) => {
            this.setLocalArea(map);
        });
        AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function() { //异步加载插件
            //输入提示
            const autoOptions = {
                input: "tipinput"
            };
            const auto = new window.AMap.Autocomplete(autoOptions);
            const select = (e, map) => {
                placeSearch.setCity(e.poi.adcode);
                placeSearch.search(e.poi.name); //关键字查询查询
            }
            const placeSearch = new AMap.PlaceSearch({
                map: map
            }); //构造地点查询类
            AMap.event.addListener(auto, "select", select); //注册监听，当选中某条记录时会触发
        });

        // 定义麻点标识
        const style = [{
            url: 'https://oms.starcharge.com/source/mass1.png',
            anchor: new AMap.Pixel(6, 6),
            size: new AMap.Size(11, 11)
        }];
        this.mass = new AMap.MassMarks([], {
            opacity: 0.8,
            zIndex: 111,
            cursor: 'pointer',
            style: style
        });

        // 定义文字块标记
        const marker = new AMap.Marker({
            content: ' ',
            map: map
        })

        // 鼠标经过麻点
        this.mass.on('mouseover', function(e) {
            marker.setPosition(e.data.lnglat);
            marker.setLabel({
                content: e.data.name
            })
        });

        // 点击麻点事件
        this.mass.on('click', (e) => {
            this.showEsDetail(e.data.id, '电站详情');
        });
    }

    // 设置mass桩群
    setMDmarkers(data, map) {
        this.mass.setData(data);
        this.mass.setMap(map);
    }

    // 设置moveEnd后的定位处理
    setLocalArea(MapApi) {
        const center = MapApi.getCenter();
        this.params['lng'] = center.lng;
        this.params['lat'] = center.lat;
        this.centerMarker.setPosition([center.lng, center.lat]);
        MapApi.getCity((r) => {
            this.params['cityStr'] = r['city'] || r['province'];
        });
    }

    // fetch 电站信息
    async fetchMap() {
        try {
            const resData = await fetchMap(this.params);
            const resObj = resData.data.data;
            const markers = [];
            for (let i of resObj) {
                i['dcStubCnt'] = `${i['dcStubCnt']}/空闲${i['stubAggStatus'][1]}`;
                i['acStubCnt'] = `${i['acStubCnt']}/空闲${i['stubAggStatus'][0]}`;
                i['stubGroupType'] = this.stubGroupType[i['stubGroupType'].toString()];
                i['type'] = this.opType[i['type'].toString()];
                let marker = {
                    'id': i['id'],
                    'name': i['name'],
                    'lnglat': [i['gisGcj02Lng'], i['gisGcj02Lat']],
                    'style': 0
                }
                markers.push(marker);
            };
            if (resData.data.code === '200') {
                this.setState({
                    gridData: resObj
                });
                this.setMDmarkers(markers, this.map);
            }
        } catch (e) {
            console.log(e);
        }
    }

    enterLoading() {
        this.setState({
            loading: !0,
            loadingmes: '查询中'
        });

        this.fetchMap().then(() => {
            this.setState({
                loading: !1,
                loadingmes: '查询'
            });
        });
    }

    // 注入关键字参数
    keywordInputHandler(e) {}

    // 注入运营类型参数
    opTypeInputHandler(v) {
        this.params['type'] = v;
    }

    // 注入电站类型参数
    esTypeInputHandler(v) {
        this.params['stubGroupType'] = v;
    }

    // 注入充电方式参数
    chargeInputHandler(v) {
        this.params['chargeMode'] = v;
    }

    // 注入功率范围参数
    rangeInputChange(e) {
        this.params['lowKw'] = parseInt(e[0]);
        this.params['highKw'] = parseInt(e[1]);
    }

    // 注入距离参数
    distanceInputChange(v) {
        this.params['distance'] = v.length ? parseInt(v) : '';
    }

    // 打开tab
    openTab(param, e) {
        this.props.onAdd.bind(window.LayoutTab)(e, param);
    }

    // 显示电站详情
    showEsDetail(id, title) {
        this.setState({
            width: 920,
            modalVisible: !0,
            modalTitle: title
        });
        this.getEsDetail(id);
    }

    // 获取电站详情
    async getEsDetail(id) {
        try {
            const resData = await getStubGroupDetail({
                stubGroupId: id
            });
            if (resData.data.code === '200') {
                const result = resData.data.data;
                this.setState({
                    modalContent: (<div className="sc-modal-scroll">
            <div className="modal-list">
              <div className={"modal-flex"}>
                <div className={"modal-flex-1"}>
                  <ul>
                    <li>
                      <strong>电站名称:</strong>
                      <span>{result.name}</span>
                    </li>
                    <li>
                      <strong>所在城市</strong>
                      <span>{result.cityStr}</span>
                    </li>
                    <li>
                      <strong>电站地址</strong>
                      <Tooltip placement="topLeft" title={result.address}>
                        <span>{result.address}</span>
                      </Tooltip>
                    </li>
                    <li>
                      <strong>运营类型</strong>
                      <span>{result.type === 1 ? '自营' : '非自营'}</span>
                    </li>
                    <li>
                      <strong>电站类型</strong>
                      <span>{this.stubGroupType[result.stubGroupType]}</span>
                    </li>
                    <li>
                      <strong>服务时间</strong>
                      <span>{result.serviceTime}</span>
                    </li>
                    <li>
                      <strong>是否带枪</strong>
                      <span>{result.hasGun === 1 ? '是' : '否'}</span>
                    </li>
                    <li>
                        <strong>车位引导</strong>
                        <Tooltip placement="topLeft" title={result.stubGroupInfo}>
                        <span>{result.stubGroupInfo}</span>
                        </Tooltip>
                    </li>
                    <li>
                      <strong>车位描述</strong>
                      <Tooltip placement="topLeft" title={result.parkingInfo}>
                      <span>{result.parkingInfo}</span>
                      </Tooltip>
                    </li>
                    <li>
                      <strong>停车费</strong>
                      <Tooltip placement="topLeft" title={result.parkingFeeInfo}>
                      <span>{result.parkingFeeInfo}</span>
                      </Tooltip>
                    </li>
                    <li>
                      <strong>电站公告</strong>
                      <span>{result.noticInfo}</span>
                    </li>
                    <li>
                      <strong>漫游状态</strong>
                      <span>{result.enableRoaming === 1 ? '漫游' : '非漫游'}</span>
                    </li>
                    <li>
                      <strong>电站状态</strong>
                      <span>{result.isBuilded === 1 ? '上线' : '下线'}</span>
                    </li>
                    <li>
                      <strong>所属商户</strong>
                      <span>{result.equipmentOwnerName}</span>
                    </li>
                    <li>
                      <strong>上线时间</strong>
                      <span>{result.startTime}</span>
                    </li>
                  </ul>
                </div>
                <div className={"modal-flex-1"}>
                  <ul>
                    <li>
                      <strong>充电价格</strong>
                      <Tooltip placement="topLeft" title={result.totalFeeInfo.replace('#', '\n')}>
                        <span>{result.totalFeeInfo.replace('#', '\n')}</span>
                      </Tooltip>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>)
                });
            }
        } catch (e) {
            console.log(e);
        }
    }

    // 取消弹窗
    cancel() {
        this.setState({
            modalVisible: !1,
            confirmLoading: !1
        });
    }

    //电站查询
    handleSearch = (value) => {
        if (!value) {
            this.params['stubGroupIds'] = null;
            this.params.keywords = null;
            return;
        }
        const res = this.findStubGroupNameTips(value);
        this.params.keywords = value;
        res.then((data) => {
            if (data) {
                const namesArr = data.map((item) => {
                    return <Option key={item.id}>{item.NAME}</Option>;
                })
                this.setState({
                    dataSource: namesArr
                });
            }
        }).catch((ex) => {
            console.log(ex);
        })

    }

    stubNameSelectHandle = (value, option) => {
        this.params['stubGroupIds'] = value;
    }

    async findStubGroupNameTips(keyword) {
        const res = await stubGroupNameTips({
            name: keyword,
            cityStr: this.params['cityStr']
        });
        return res.data.data;
    }

    render() {
        const Content = <div className="sc-page-content">
      <div className="page-toolbar">
        <Row gutter={8}>
          <Col lg={8} xl={4}>
            <Select placeholder="运营类型" onChange={this.opTypeInputHandler.bind(this)}>
              <Option value="">全部</Option>
              <Option value="0">非自营</Option>
              <Option value="1">自营</Option>
            </Select>
          </Col>
          <Col lg={8} xl={4}>
            <Select placeholder="电站类型" onChange={this.esTypeInputHandler.bind(this)}>
              <Option value="">全部</Option>
              <Option value="0">公共</Option>
              <Option value="1">个人</Option>
              <Option value="2">专用开放</Option>
              <Option value="3">专用内部</Option>
            </Select>
          </Col>
          <Col lg={8} xl={4}>
            <Select placeholder="充电方式" onChange={this.chargeInputHandler.bind(this)}>
              <Option value="">全部</Option>
              <Option value="0">交流电站</Option>
              <Option value="1">直流电站</Option>
              <Option value="2">高压快充电站</Option>
            </Select>
          </Col>
          <Col lg={4} xl={2}>
            <label>电桩功率</label>
          </Col>
          <Col lg={4} xl={4}>
            <Slider range step={1} defaultValue={[0, 500]} max={1000} onAfterChange={this.rangeInputChange.bind(this)}/>
          </Col>
          <Col lg={8} xl={4}>
            <Select defaultValue={`10公里`} onChange={this.distanceInputChange.bind(this)}>
              <Option value="">全部</Option>
              <Option value="10">10公里</Option>
              <Option value="20">20公里</Option>
              <Option value="30">30公里</Option>
              <Option value="40">40公里</Option>
              <Option value="50">50公里</Option>
            </Select>
          </Col>
          <Col lg={8} xl={8}>
            <AutoComplete dataSource={this.state.dataSource} onSelect={this.stubNameSelectHandle} onSearch={this.handleSearch} placeholder="电站名称"/>
          </Col>
        </Row>
        <Row>
          <Col className="btn-group-rt">
            <Button type="primary" loading={this.state.loading} onClick={this.enterLoading.bind(this)}>{this.state.loadingmes}</Button>
          </Col>
        </Row>
      </div>
      <div className="pc-map" id="mapContainer">
      </div>
      <div id="myPageTop">
        <table>
          <tr>
            <td>
              <label>请输入关键字：</label>
            </td>
          </tr>
          <tr>
            <td>
              <input id="tipinput"/>
            </td>
          </tr>
        </table>
      </div>
      <div className="page-panel">
        <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns}  pagination={this.state.pagination}/>
        <ScModal
        width={this.state.width}
        modalVisible={this.state.modalVisible}
        modalTitle={this.state.modalTitle}
        modalContent={this.state.modalContent}
        footer={null}
        cancel={this.cancel.bind(this)}
        />
      </div>
    </div>;

        return Content;
    }
}

export default PsDetail;

PsDetail.propTypes = {
    onAdd: PropsType.func
}